package sv.gob.mh.dgii.security;

import java.util.Collection;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetails;
import org.springframework.security.ldap.userdetails.LdapUserDetailsMapper;
import sv.gob.mh.dgii.common.Utils;

public class DGIILdapUserDetailsMapper extends LdapUserDetailsMapper {
	
	private static final String DEFAULT_NIT = "00000000000000";
	private static final String DEFAULT_UNIDAD = "01010";
	private static final String DEFAULT_ADM_TRIB = "01";
	private static final String DEFAULT_UBICACION_FISICA = "Sin ubicacion";
	
	

	@Override
	public UserDetails mapUserFromContext(DirContextOperations ctx,
			String username, Collection<? extends GrantedAuthority> authorities) {
		
		String newUsername = username.toLowerCase();
		
		LdapUserDetails ud = (LdapUserDetails)super.mapUserFromContext(ctx, newUsername, authorities);
		DGIIUserDetailsImpl userDetails = new DGIIUserDetailsImpl(ud);
		
		userDetails.setEmail(((String) ctx.getObjectAttribute("mail")).trim());
		userDetails.setDisplayName((String) ctx
				.getObjectAttribute("displayname"));

		String nit = (String) ctx.getObjectAttribute("nit");
		String ubicacionFisica = (String) ctx.getObjectAttribute("ubicaFisica");
		String adminTri = (String) ctx.getObjectAttribute("adminTrib");
		String cunidad = (String) ctx.getObjectAttribute("unidad");

		if (!Utils.isNullOrEmpty(nit)) {
			userDetails.setNit(nit.trim());
		} else {
			userDetails.setNit(DEFAULT_NIT);

		}

		if (!Utils.isNullOrEmpty(cunidad)) {
			userDetails.setUnidad(cunidad.trim());
		} else {
			userDetails.setUnidad(DEFAULT_UNIDAD);
		}

		if (!Utils.isNullOrEmpty(ubicacionFisica)) {
			userDetails.setUbicacionFisica(ubicacionFisica);
		} else {
			userDetails.setUbicacionFisica(DEFAULT_UBICACION_FISICA);

		}

		if (!Utils.isNullOrEmpty(adminTri)) {
			userDetails.setCadmTrib(adminTri.trim());
		} else {
			userDetails.setCadmTrib(DEFAULT_ADM_TRIB);
		}

		return userDetails;
	}
}